import {
  setStyle,
  getInnerStr,
  cryptoEscape
} from "./utils";
import {PRIVATEKEY} from './consts'
import CryptoJS from 'crypto-js';

function Weditor(options) {
  this._id = 0;
  this._init(options);
}

Weditor.prototype = {
  /**
   * 初始化
   * 添加样式
   * @private
   */
  _init(){
    setStyle();
  },
  /**
   * 点击占位符的主要功能
   * @param ele
   */
  open(ele) {
    // todo 统计埋点
    var rawStr = ele.getAttribute('data-meta');
    var encryptedStr = cryptoEscape(rawStr, false);
    var key = CryptoJS.enc.Hex.parse("000102030405060708090a0b0c0d0e0f");
    var iv = CryptoJS.enc.Hex.parse("101112131415161718191a1b1c1d1e1f");
    try {
      var decryptedBytes = CryptoJS.AES.decrypt(encryptedStr.toString(), key, {iv: iv});
      var objData = JSON.parse(decryptedBytes.toString(CryptoJS.enc.Utf8));
    } catch (e) {
      var decryptedBytes = CryptoJS.AES.decrypt(encryptedStr.toString(), PRIVATEKEY);
      var objData = JSON.parse(decryptedBytes.toString(CryptoJS.enc.Utf8));
    }
    console.log(objData);
    if (objData && objData.type) {
      this.show(objData, objData.type);
    }
  },
  show(config, type) {
    var container = document.createElement("div");
    container.style.cssText = "width: 100%;height: 100%;position: fixed;top: 0;left: 0;bottom: 0;right: 0;background: rgba(0,0,0,.7);z-index: 1000;";
    container.className = 'weditor-mask-in';
    container.innerHTML = getInnerStr(config, type);
    container.addEventListener('click', function (event) {
      var target = event.target || event.srcElement;
      if(target.className === "weditor-close-btn"){
        this.className = "weditor-mask-out";
        this.firstElementChild.className = "weditor-modal-out";
        var _this = this;
        setTimeout(function () {
          document.body.removeChild(_this);
          // todo 需不需要移除事件处理程序？
        }, 150);
      }
    }, false)
    document.body.appendChild(container);
  }
}
Object.defineProperty(Weditor.prototype, 'constructor', {
  enumerable: false,
  value: Weditor
})

const wed = new Weditor();
window.weditor = wed;

export default wed;
